import struct, socket, time, urllib, urllib2
try:
    def attack():
        host = "192.168.0.100"
        port = 25565
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        logindata = {'user':'SeR', 'password':'1234', 'version':'29'}
        data = urllib.urlencode(logindata)
        data = {'user':u'SeR','host':u'192.168.0.100','port':25565}
        mcsessionid = logindata['user']

        stringfmt = u'%(user)s;%(host)s:%(port)d'
        string = stringfmt % data
        structfmt = '>bh'
        packetbytes = struct.pack(structfmt, 2, len(string))+string.encode('utf-16BE')
        s.send(packetbytes)
        connhash = s.recv(1024)

        print ("Connection Hash: " + connhash)
        print ('Sending data to http://session.minecraft.net/game/joinserver.jsp?user='+data['user']+'&sessionId=' + mcsessionid + '&serverId=' + connhash)
        req = urllib.urlopen('http://session.minecraft.net/game/joinserver.jsp?user='+data['user']+'&sessionId=' + mcsessionid + '&serverId=' + connhash)

        returndata = req.read()
        if(returndata == 'OK'):
            print('session.minecraft.net says everything is okay, proceeding to send data to server.')
        else:
            print('Oops, something went wrong.')

        time.sleep(5)

        # All above here works perfectly.
        enc_user = data['user'].encode('utf-16BE')
        #This line is probably where something's going wrong:
        packfmt = '>bih{}shiibBB'.format(len(enc_user))
        packetbytes = struct.pack(packfmt, 1, 23, len(data['user']), enc_user, 0, 0, 0, 0, 0, 0)
        print('Sending ' + packetbytes + ' to server.')
        s.send(packetbytes)
        s.close()
except:
    while 1:
        attack() 
    
while 1:
    attack()

raw_input('end')
